    //
//  editWatchList.m
//  iStock Global
//
//  Created by Andy on 2010/11/15.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "editWatchList.h"
#import "addStockInWatchList.h"
#import "TableCellAddStockWatchList.h"
#import "UIButton+Glossy.h"
@implementation editWatchList
@synthesize delegate,AppleDeglate  ; 
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
      
    }
    return self;
}
-(id)initWithWatchListCode:(NSMutableArray *)watchlistcode 
			 WatchListName:(NSMutableArray *)watchlistname
		WatchList_id_class:(NSMutableArray *)aWatchList_id_class			
			watchlistTitle:(NSString *)Title{
	self= [super init];
    if (self) {
		array_watchlist_code=watchlistcode;
		array_watchlist_name=watchlistname;
		array_watchlist_id_class=aWatchList_id_class;
		//for (NSString *J in array_watchlist_id_class ) {
			
		//	NSLog(@"%@",J);			
		//}
		
		self.title=Title;
	}
	return self;
}
 


-(void)get_navcontroller:(navcontroller *)nd{
	
	
	navdelegete=nd;
	UIBarButtonItem *addButton = [[UIBarButtonItem alloc]             
								   initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self
								   action:@selector(addStockInWatchList)]; 
	self.navigationItem.rightBarButtonItem = addButton;	
	
	 
	
	editButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	editButton.frame=CGRectMake(0,0, 150, 30 );
	 
	//按鈕變色 使用於 UIButtonTypeRoundedRect
	//要加入 UIButton+Glossy.m UIButton+Glossy.h
	[editButton setBackgroundToGlossyRectOfColor:[UIColor yellowColor] withBorder:YES forState:UIControlStateNormal];
	[editButton setBackgroundToGlossyRectOfColor:[UIColor redColor] withBorder:YES forState:UIControlStateHighlighted];

	
	// editButton.frame = CGRectMake(0,0, 150, 30 ); // position in the parent view and set the size of the button
     
	
	[editButton setTitle:@" Edit " forState:UIControlStateNormal];
    [editButton addTarget:self action:@selector(editwatchlist_DeleteSort) forControlEvents:UIControlEventTouchUpInside];            
	 editButton.backgroundColor= [UIColor clearColor];	
	[editButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
	//[editButton setBackgroundColor:[UIColor yellowColor]];
	 
	
	
	self.navigationItem.titleView=  editButton;
	
	
} 
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	 
	UIView *mainview;
	mainview=[[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
	self.view=mainview;
    [mainview release];
    
	self.view.backgroundColor=[UIColor lightTextColor];	
	 
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        
        myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 700.0f)  style:UITableViewStylePlain];
    }    
	else{
        
        myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, self.view.frame.size.height)  style:UITableViewStylePlain];
    }
	
	
    
    
    
	myTable.dataSource = self;	
	myTable.delegate=self;	 
	[self.view addSubview:myTable];
	[myTable reloadData];
	
    [self editwatchlist_DeleteSort];
	 
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
 

}

-(void)addStockInWatchList{
	 
	NSLog(@"addStockInWatchList");
	 
	
	addStockInWatchList *ediw;
	//ediw=[[addStockInWatchList alloc] initWithNibName:nil bundle:nil];
	ediw=[[addStockInWatchList alloc] initWithWatchListCode:array_watchlist_code WatchListName:array_watchlist_name WatchListIdClass:array_watchlist_id_class watchlistTitle:self.title];
	
	ediw.delegate=self;
    ediw.AppleDeglate=AppleDeglate;
	ediw.modalTransitionStyle =UIModalTransitionStyleCoverVertical; 
	 
	
	 [navdelegete pushViewController:ediw animated:NO];
	
	 [ediw release];	
	
}

 
-(void)editwatchlist_DeleteSort{
	NSLog(@"editwatchlist_DeleteSort");
	
	[editButton setTitle:@" Save " forState:UIControlStateNormal];
	
	[editButton removeTarget:self action:@selector(editwatchlist_DeleteSort) forControlEvents:UIControlEventTouchUpInside];            	 
	[editButton addTarget:self action:@selector(savewatchlistok) forControlEvents:UIControlEventTouchUpInside];            
	
	
	[myTable setEditing:YES animated:YES];

}
-(void)savewatchlistok{
    NSLog(@"save editwatchlist_DeleteSort");
	
	
	[editButton setTitle:@" Edit " forState:UIControlStateNormal];
   
	[editButton removeTarget:self action:@selector(savewatchlistok) forControlEvents:UIControlEventTouchUpInside];            
	[editButton addTarget:self action:@selector(editwatchlist_DeleteSort) forControlEvents:UIControlEventTouchUpInside];            
	
	
	[self savewatchlist];
    [myTable setEditing:NO animated:YES];	
	
	
	
	
}

//刪除用
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
	if (editingStyle==UITableViewCellEditingStyleDelete) {
	 	 			
			[array_watchlist_code removeObjectAtIndex:indexPath.row];
			[array_watchlist_name removeObjectAtIndex:indexPath.row];
			[array_watchlist_id_class removeObjectAtIndex:indexPath.row];		
		
		    [tableView deleteRowsAtIndexPaths: [NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
		
		    //[self savewatchlist];		  
		    /*
			if ([classd count]==1) {
				[classd addObject:@"Watch List Sample"];
			}
			 
			
			//儲存自選股
			NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
			NSString *dir = [paths objectAtIndex:0];
			NSString *filePathw;
			filePathw = [[NSString alloc] initWithString:[dir stringByAppendingPathComponent:@"WatchListClass.plist"]];
			NSMutableArray *tempclassd;
			tempclassd=[[NSMutableArray alloc] init];
			for (int i=1; i<[classd count]; i++) {
				[tempclassd addObject:[classd objectAtIndex:i]];
			}
			
			[tempclassd writeToFile:filePathw atomically:NO];	
			//重新載入資料
			[self datasql];	
			 */
			[myTable reloadData];
		 
		
		
	}
	
}
-(void)savewatchlist{
	//儲存自選股
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *dir = [paths objectAtIndex:0];
	NSString *filePathw;
	filePathw = [[NSString alloc] initWithString:[dir stringByAppendingPathComponent:[NSString stringWithFormat: @"WatchList_%@.cplist",self.title]]];
	NSMutableArray *awr;
	awr=[[NSMutableArray alloc] init];
	 
	for (int i=0; i<[array_watchlist_code count]; i++) {
		NSString *wr;
		wr=[NSString stringWithFormat:@"%@_%@_%@_34.5_56000",[array_watchlist_code objectAtIndex:i],[array_watchlist_name objectAtIndex:i],[array_watchlist_id_class objectAtIndex:i]];
		[awr addObject:wr];
	}
    
    
	
	
	[awr writeToFile:filePathw atomically:NO];
	[awr release];
    [filePathw release];
}


-(void)editwatchlist{
	
	[self savewatchlist];
	
	//回到上層事件執行
	 [self.delegate editWatchListControllerDidFinish:self];

}

- (void)addStockInWatchLisControllerDidFinish:(addStockInWatchList *)controller{
	[myTable reloadData];
	NSLog(@"完成自選股增設股");
}

//Table 行與格資料設定
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	return [array_watchlist_code count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	static NSString *CellIdentifier = @"Cell";
    
    TableCellAddStockWatchList *cell =(TableCellAddStockWatchList *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[TableCellAddStockWatchList alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
	
    //cell.code.text=[array_watchlist_code objectAtIndex: indexPath.row];
    //標記:是否移除交易所碼        
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	
    
    if ([[prefs objectForKey:@"isRemoveExchangeCode"] boolValue]==YES) {
        //字串分割
        NSArray *code_exchange_Array = [[array_watchlist_code objectAtIndex: indexPath.row] componentsSeparatedByString:@"."];
        if ([code_exchange_Array count]==2) {
            cell.code.text=[code_exchange_Array objectAtIndex:0];
        }
        else{
            cell.code.text=[array_watchlist_code objectAtIndex: indexPath.row];         
        }
        
    }
    else {
        cell.code.text=[array_watchlist_code objectAtIndex: indexPath.row];
    }            
    
    
    
    cell.name.text=[array_watchlist_name objectAtIndex: indexPath.row];	
    cell.id_class.text=[array_watchlist_id_class objectAtIndex: indexPath.row];	
	
	return cell;	
	
	
	
}
#pragma mark -
#pragma mark  Table的HeaderInSection 外觀與高度設定

//調整HeaderInSection 高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
	return 0;
}
//HeaderInSection 增加物件
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
	
  	UIView* customView = [[[UIView alloc] initWithFrame:CGRectMake(30.0, 0.0, 100.0, 200.0)] autorelease];
  	
	
	//section 底色設定
	customView.backgroundColor = [UIColor colorWithRed:16.0/255.0 green:42.0/255.0 blue:64.0/255.0 alpha:1.0];	
	//alpha 透明度 0.1:幾乎透明 1:不透明
	      
			
		 	
	 	return customView;
}
/*
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
	 	//消除鍵盤用
	//[addw resignFirstResponder];
	
	[array_watchlist_code addObject:[[[addw text] uppercaseString] copy]];
	[array_watchlist_name addObject:[[[addw text] uppercaseString] copy]];
	
	[myTable reloadData];
	addw.text=@"";
	return NO;
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
-(void)viewWillDisappear:(BOOL)animated{
	 //利用[[navdelegete viewControllers] count] 來判斷第幾層 來決定是否要用刷新動作
	   NSLog(@"[[navdelegete viewControllers] count]=%i", [[navdelegete viewControllers] count] );
	if ([[navdelegete viewControllers] count] <=3)
	 [self editwatchlist];

}
 


- (void)viewDidUnload {
	 
	
    [super viewDidUnload];
    
}


- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark  表格排序專用 
//要將兩個tableView:的委託事件同時放上去才會出現排序選項
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
	return YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
	  toIndexPath:(NSIndexPath *)toIndexPath{
	
	NSString *code = [[array_watchlist_code objectAtIndex:fromIndexPath.row] retain];
	[array_watchlist_code removeObjectAtIndex:fromIndexPath.row];
	[array_watchlist_code insertObject:code atIndex:toIndexPath.row];
	[code release];
	
	
	NSString *name = [[array_watchlist_name objectAtIndex:fromIndexPath.row] retain];
	[array_watchlist_name removeObjectAtIndex:fromIndexPath.row];
	[array_watchlist_name insertObject:name atIndex:toIndexPath.row];
	[name release];
	
	NSString *id_class = [[array_watchlist_id_class objectAtIndex:fromIndexPath.row] retain];
	[array_watchlist_id_class removeObjectAtIndex:fromIndexPath.row];
	[array_watchlist_id_class insertObject:id_class atIndex:toIndexPath.row];
	[id_class release];	
}




@end
